package com.wanwanbookstore.servlet;

import com.wanwanbookstore.dao.UserDAO;
import com.wanwanbookstore.entity.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

public class UserCenterServlet extends HttpServlet {
    private UserDAO userDAO = new UserDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        // 重新从数据库获取最新的用户信息
        user = userDAO.getUserById(user.getId());
        session.setAttribute("user", user);

        request.getRequestDispatcher("user_center.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        // 获取操作类型
        String action = request.getParameter("action");
        
        if (action == null) {
            action = "basic";
        }
        
        switch (action) {
            case "basic":
                updateBasicInfo(request, session, user);
                break;
            case "username":
                updateUsername(request, session, user);
                break;
            case "password":
                updatePassword(request, session, user);
                break;
            case "delete":
                // 处理账号注销
                deleteAccount(request, response, session, user);
                return; // 注销后直接返回，不继续执行后续代码
        }
        
        // 重新获取最新的用户信息
        user = userDAO.getUserById(user.getId());
        session.setAttribute("user", user);
        request.getRequestDispatcher("user_center.jsp").forward(request, response);
    }
    
    private void updateBasicInfo(HttpServletRequest request, HttpSession session, User user) {
        // 更新基本信息（电话和地址）
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");

        user.setPhone(phone);
        user.setAddress(address);

        if (userDAO.updateUser(user)) {
            session.setAttribute("user", user);
            request.setAttribute("successMessage", "联系方式更新成功");
        } else {
            request.setAttribute("errorMessage", "联系方式更新失败，请重试");
        }
    }
    
    private void updateUsername(HttpServletRequest request, HttpSession session, User user) {
        // 更新用户名
        String newUsername = request.getParameter("newUsername");
        String confirmUsername = request.getParameter("confirmUsername");
        
        // 验证输入
        if (newUsername == null || newUsername.trim().isEmpty()) {
            request.setAttribute("errorMessage", "用户名不能为空");
            return;
        }
        
        if (!newUsername.equals(confirmUsername)) {
            request.setAttribute("errorMessage", "两次输入的用户名不一致");
            return;
        }
        
        // 检查用户名是否已存在
        if (userDAO.checkUsernameExists(newUsername, user.getId())) {
            request.setAttribute("errorMessage", "该用户名已被使用，请选择其他用户名");
            return;
        }
        
        if (userDAO.updateUsername(user.getId(), newUsername)) {
            user.setUsername(newUsername);
            session.setAttribute("user", user);
            request.setAttribute("successMessage", "用户名更新成功");
        } else {
            request.setAttribute("errorMessage", "用户名更新失败，请重试");
        }
    }
    
    private void updatePassword(HttpServletRequest request, HttpSession session, User user) {
        // 更新密码
        String currentPassword = request.getParameter("currentPassword");
        String newPassword = request.getParameter("newPassword");
        String confirmPassword = request.getParameter("confirmPassword");
        
        // 验证当前密码
        if (!user.getPassword().equals(currentPassword)) {
            request.setAttribute("errorMessage", "当前密码输入错误");
            return;
        }
        
        // 验证新密码
        if (newPassword == null || newPassword.length() < 6) {
            request.setAttribute("errorMessage", "新密码长度不能少于6位");
            return;
        }
        
        if (!newPassword.equals(confirmPassword)) {
            request.setAttribute("errorMessage", "两次输入的新密码不一致");
            return;
        }
        
        if (userDAO.updatePassword(user.getId(), newPassword)) {
            user.setPassword(newPassword);
            session.setAttribute("user", user);
            request.setAttribute("successMessage", "密码更新成功");
        } else {
            request.setAttribute("errorMessage", "密码更新失败，请重试");
        }
    }
    
    /**
     * 处理账号注销逻辑
     */
    private void deleteAccount(HttpServletRequest request, HttpServletResponse response, HttpSession session, User user) throws ServletException, IOException {
        // 获取并验证密码
        String password = request.getParameter("confirmDeletePassword"); // 注意这里要与前端表单字段名对应
        if (!user.getPassword().equals(password)) {
            request.setAttribute("errorMessage", "密码错误，无法注销账号");
            request.getRequestDispatcher("user_center.jsp").forward(request, response);
            return;
        }
        
        // 执行软删除
        if (userDAO.softDeleteUser(user.getId())) {
            // 清除用户会话
            session.invalidate();
            
            // 重定向到登录页面，并添加注销成功的提示
            response.sendRedirect("login?message=account_deleted");
        } else {
            request.setAttribute("errorMessage", "账号注销失败，请稍后重试");
            request.getRequestDispatcher("user_center.jsp").forward(request, response);
        }
    }
}